import { Text, View, SafeAreaView, Dimensions, StyleSheet, Image, TouchableOpacity, TouchableWithoutFeedback, TextInput, Modal } from 'react-native'
import React, { Component, createRef, useState } from 'react'
import { ImagePreview } from '@pingtou/rn-vant';
import { ListView } from '@ant-design/react-native'
import { pTx } from "../../utils/dimensions"
import httpApi from "../../api"
import { grade } from "../../utils/grade"
import ReleasePost from "../../components/releasePost"
import IconFont from '@pingtou/rn-vant-icons'
import CommunityDetails from "./communityDetails"
import ImageEquallyEnlarge from "../../components/imageEquallyEnlarge"
import ImageView from "react-native-image-viewing";



export class Community extends Component {
    constructor(props) {
        super(props)
        this.state = {
            active: 0,
            openPostComment: false,
            comment: "",
            postId: "",
            index: 0,
            sendPostCommentLoading: false,
            images: [],
            imageIndex: 0,
            visible: false
        }
        this.listViewRefs = createRef();
        this.releasePostRefs = createRef();
        this.textInputRefs = createRef();
        this.communityDetailsRefs = createRef();

    }
    onFetch = async (pageNum = 1, startFetch, abortFetch,) => {
        try {
            let pageSize = 5
            const res = await httpApi.getPostList({ pageNum: (pageNum - 1), pageSize })
            startFetch(res.data.PostList, pageSize)
        } catch (err) {
            abortFetch()
        }
    }

    loadMoregetPostCommentList = async (id, len, index) => {
        let rowData = this.listViewRefs.current.ulv.getRows();
        const res = await httpApi.getPostCommentList({ pageNum: Math.ceil(len / 10), pageSize: 10, postId: id })
        const commentListItem = res.data.PostCommentList
        rowData[index].commentList = rowData[index].commentList.concat(commentListItem || [])
        this.listViewRefs.current.ulv.updateDataSource(rowData)
    }

    textInputRefsfocus = (id, index) => {
        this.setState({ openPostComment: true, postId: id, index: index })
        setTimeout(() => {
            this.textInputRefs.current?.focus()
        }, 600)
    }

    sendPostComment = async (item) => {
        try {
            let rowData = this.listViewRefs.current.ulv.getRows();
            console.log(rowData.find(ite => ite.Id == item.Id))
            rowData.forEach(ite => {
                if (ite.Id == item.Id) {
                    ite.Comments = ite.Comments + 1
                }
            })
            this.listViewRefs.current.ulv.updateDataSource(rowData)
        } catch (error) {
        }
    }

    renderItem = (item, index) => {
        return (
            <View style={styles.renderItemli} key={index}>
                <Image style={styles.ProfilePhoto} source={{ uri: httpApi.inline + item.ProfilePhoto }}></Image>
                <View style={styles.PostContainer}>

                    <TouchableWithoutFeedback onPress={() => this.communityDetailsRefs.current.setcommunityDetails(item)}>
                        <View>
                            <View style={styles.PostContainerUserInfo}>
                                <View style={styles.infoCotent}>
                                    <Text style={styles.NickName}>{item.NickName}</Text>
                                    <Image style={styles.infoCotentImage} source={grade[item.UserLevel]}></Image>
                                </View>
                                <Text style={styles.timr}>{item.CreatedAt}</Text>
                            </View>
                            <View style={styles.ContentInfo}>
                                {item.Content ? <Text style={styles.Content}>{item.Content}</Text> : ""}
                                {item.Image ?
                                    <View style={styles.ContentImageList}>

                                        {
                                            item.Image?.split(',').map((img, i) => {
                                                let image = item.Image?.split(',').map(item => { return { uri: httpApi.inline + item } })
                                                const length = image.length
                                                return (
                                                    <TouchableWithoutFeedback
                                                        onPress={() => this.setState({
                                                            visible: true,
                                                            images: image,
                                                            imageIndex: i
                                                        })}
                                                        key={i}
                                                    >
                                                        <View>

                                                            {
                                                                length == 1 ?
                                                                    <ImageEquallyEnlarge
                                                                        source={{ uri: httpApi.inline + img }}
                                                                        width={pTx(220)}
                                                                    />
                                                                    :
                                                                    <Image
                                                                        style={[styles.ContentImageItem]}
                                                                        source={{ uri: httpApi.inline + img }}></Image>
                                                            }
                                                        </View>
                                                    </TouchableWithoutFeedback>
                                                )
                                            })
                                        }
                                    </View>
                                    : ""}
                            </View>
                        </View>
                    </TouchableWithoutFeedback>
                    <View style={styles.CommentsQuantityObx}>
                        <View style={styles.CommentsQuantityObxCell}>
                            <Image style={styles.CommentsIcon} source={require('../../assets/image/icon16.png')}></Image>
                            <Text style={styles.postCommentValue}>{item.Likes}</Text>
                        </View>
                        <TouchableOpacity onPress={() => this.communityDetailsRefs.current.setcommunityDetails(item)}>
                            <View style={styles.CommentsQuantityObxCell}>
                                <Image style={styles.CommentsIcon} source={require('../../assets/image/icon17.png')}></Image>
                                <Text style={styles.postCommentValue}>{item.Comments}</Text>
                            </View>
                        </TouchableOpacity>
                        <View style={styles.CommentsQuantityObxCell}>
                            <Image style={styles.CommentsIcon} source={require('../../assets/image/icon18.png')}></Image>
                            <Text style={styles.postCommentValue}>{item.Favorites}</Text>
                        </View>
                    </View>
                </View>
            </View>
        )
    }

    render() {
        return (
            <SafeAreaView style={styles.container}>
                <View style={styles.head}>
                    <View style={[styles.headRow, styles.currentHeadRowText]}>
                        <Text style={styles.headRowText, { fontSize: pTx(18), fontWeight: "bold", color: "#0A0C14" }}>
                            推荐
                        </Text>
                    </View>
                    <View style={styles.headRow}>
                        <Text style={styles.headRowText}>
                            关注
                        </Text>
                    </View>
                    <View style={styles.headRow}>
                        <Text style={styles.headRowText}>
                            社群
                        </Text>
                    </View>
                    <View style={styles.headRow}>
                        <Text style={styles.headRowText}>
                            短剧
                        </Text>
                    </View>
                </View>
                <ListView
                    ref={this.listViewRefs}
                    onFetch={this.onFetch}
                    keyExtractor={(item, index) => `${index} - ${item}`}
                    renderItem={this.renderItem}
                    numColumns={1}
                />
                <ImageView
                    images={this.state.images}
                    imageIndex={this.state.imageIndex}
                    visible={this.state.visible}
                    onRequestClose={() => this.setState({ visible: false })}
                />
                <TouchableOpacity style={styles.release} onPress={() => this.releasePostRefs.current.setVisible(true)}>
                    <Image style={styles.releaseImage} source={require('../../assets/image/release.png')}></Image>
                </TouchableOpacity>
                <ReleasePost ref={this.releasePostRefs} loadOnFetch={() => this.listViewRefs.current.refresh()} />

                <CommunityDetails ref={this.communityDetailsRefs} sendPostComment={(item) => this.sendPostComment(item)} />
            </SafeAreaView>
        )
    }
}

export default Community


const styles = StyleSheet.create({
    container: {
        position: "relative",
        flex: 1,
        backgroundColor: "#fff",
    },
    head: {
        flexDirection: 'row',
        paddingHorizontal: pTx(15),
        paddingVertical: pTx(15),
    },
    headRow: {
        marginRight: pTx(20),
        paddingBottom: pTx(5),
    },
    headRowText: {
        fontSize: pTx(16),
        color: "#0A0C14",
    },
    currentHeadRowText: {
        borderBottomWidth: pTx(2),
        borderBottomColor: "#06C161"
    },
    release: {
        position: "absolute",
        bottom: pTx(14),
        right: pTx(3),
    },

    releaseImage: {
        width: pTx(74),
        height: pTx(74),
    },

    renderItemli: {
        marginTop: pTx(16),
        flexDirection: 'row',
        paddingHorizontal: pTx(15),
    },
    ProfilePhoto: {
        width: pTx(41),
        height: pTx(41),
        backgroundColor: "#EDEDED",
        borderRadius: pTx(6),
    },
    PostContainer: {
        marginLeft: pTx(8),
    },
    PostContainerUserInfo: {

    },
    infoCotent: {
        flexDirection: 'row',
        alignItems: "center"
    },
    infoCotentImage: {
        width: pTx(34),
        height: pTx(16),
    },
    NickName: {
        fontSize: pTx(16),
        color: "#0A0C14"
    },
    timr: {
        marginTop: pTx(7),
        fontSize: pTx(12),
        color: "#AFB5BD",
    },
    ContentInfo: {
        marginTop: pTx(13),
        maxWidth: pTx(290)
    },
    Content: {
        fontSize: pTx(15),
        color: "#0A0C14"
    },
    ContentImageList: {
        marginTop: pTx(8),
        flexDirection: 'row',
        flexWrap: "wrap",
        width: pTx(290)
    },
    ContentImageItem: {
        width: pTx(90),
        height: pTx(90),
        marginRight: pTx(5),
        marginBottom: pTx(5),
        borderRadius: pTx(4),
        backgroundColor: "#EDEDED",
    },
    postComment: {
        marginTop: pTx(10),
        width: pTx(296),
        paddingVertical: pTx(6),
        backgroundColor: "rgba(237,237,237,0.3)",
        borderRadius: pTx(3),
    },
    postCommentCell: {
        paddingHorizontal: pTx(12),
        paddingVertical: pTx(6),
        fontSize: pTx(14),
        color: "#0A0C14"
    },
    CommentsQuantityObx: {
        marginTop: pTx(12),
        paddingBottom: pTx(16),
        flexDirection: 'row',
        borderBottomColor: "rgba(175,181,189,0.15)",
        borderBottomWidth: 1,
    },
    CommentsQuantityObxCell: {
        flexDirection: 'row',
        alignItems: "center",
        marginRight: pTx(32),
    },
    CommentsIcon: {
        marginRight: pTx(3),
        width: pTx(14),
        height: pTx(14),
        padding: pTx(1),
    },
    postCommentValue: {
        fontSize: pTx(10),
        color: "#A6A8B3"
    }
})